
#include "StdAfx.h"

#ifndef DEF_VC6

#include "HttpUpload.h"
#include <LogService.h>
#include <FileObj.h>

#pragma comment( lib, "libcurl_imp.lib" )

HttpUpload::HttpUpload(){
	handle_ = curl_easy_init();

	curl_global_init( CURL_GLOBAL_ALL );
}

HttpUpload::~HttpUpload(){
}

size_t HttpUpload::callback_read_upload( void *ptr, size_t size, size_t nmemb, void* stream ){	
	FILE* file = (FILE*)stream;
	if(! file )
		return 0;

	size_t result = fread( ptr, size, nmemb, file );

	LOG_FUNC( LOG_SERVICE( "instance" )->Log("*** We read %d bytes from file", result ) );	
 
	return result;
}

int HttpUpload::upload_file( char* url, char* file ){
	if(! handle_ )
		return -1;

	if(! url )
		return -1;

	if(! file )
		return -1;

	FileObj target_file;
	if(! target_file.open( file, "rb" ) )
		return -1;	

	curl_easy_setopt( handle_, CURLOPT_READFUNCTION, callback_read_upload );
	curl_easy_setopt( handle_, CURLOPT_UPLOAD, 1L );
    curl_easy_setopt( handle_, CURLOPT_PUT, 1L );
    curl_easy_setopt( handle_, CURLOPT_URL, url );
    curl_easy_setopt( handle_, CURLOPT_READDATA, target_file.getHandle() );
    curl_easy_setopt( handle_, CURLOPT_INFILESIZE_LARGE, (curl_off_t)target_file.getSize() );
	
	curl_easy_perform( handle_ );

	return 0;
}

#endif
